package com.databing.demo.base

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.databing.demo.R
import com.databing.demo.annotation.ClazzInfo
import com.databing.demo.config.INTENT_FILE_PREFIX
import com.databing.demo.config.INTENT_TITLE
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration

/**
 * 创建日期：2020/10/31
 * 描述:用于解析ChapterActivity的解析
 * 作者:支豪亮
 */
abstract class ChapterActivity : TitleActivity(), IInfoCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_chapter)
        val recyclerView = findViewById<RecyclerView>(R.id.rcl_chapter)

        recyclerView.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(this)
                .color(Color.LTGRAY)
                .sizeResId(R.dimen.divider)
                .marginResId(R.dimen.divider_margin, R.dimen.divider_margin)
                .build()
        )

        val chapter = initChapterInfo()
        recyclerView.adapter =
            ChapterAdapter(initActivityList(chapter.chapter, chapter.order), this)
    }

    abstract fun initChapterInfo(): ChapterInfo


    private fun initActivityList(chapter: Int = 0, order: Int = 0): List<InfoBean> {
        val mInfoBeanList: MutableList<InfoBean> = ArrayList()
        val packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
        for (info in packageInfo.activities) {
            val clazz = Class.forName(info.name)
            val hasAnnotation: Boolean =
                clazz.isAnnotationPresent(ClazzInfo::class.java)
            if (hasAnnotation) {
                val infoAnnotation = clazz.getAnnotation(ClazzInfo::class.java) ?: continue
                val infoBean = InfoBean(
                    infoAnnotation.chapter,
                    infoAnnotation.order,
                    infoAnnotation.title,
                    infoAnnotation.desc,
                    info.name
                )
                if (chapter == 0 && infoAnnotation.order == 0 && order == 0) {
                    mInfoBeanList.add(infoBean)
                } else if (chapter == infoAnnotation.chapter && infoAnnotation.order != 0) {
                    mInfoBeanList.add(infoBean)
                }

            }
        }

        //item.chapter 左移增加排序的chapter的权重
        mInfoBeanList.sortBy { item -> (item.chapter shl 8) + item.order }
        return mInfoBeanList
    }

    override fun onClick(infoBean: InfoBean) {
        val intent = Intent()
        intent.component = ComponentName(this, infoBean.clazzName)
        intent.putExtra(INTENT_TITLE, "${infoBean.title} ${infoBean.desc}")
        intent.putExtra(INTENT_FILE_PREFIX,"${infoBean.chapter}.${infoBean.order}")
        startActivity(intent)
    }
}

